package sz.szsmk.citizencard.ui.activity;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chenenyu.router.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.SearchAllActivityBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.gover.FunctionItem;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.model.network.bean.response.CloudFlashRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.SimpleRes;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealName2Res;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.contract.ISearchAllContact;
import sz.szsmk.citizencard.mvp.presenter.SearchAllPresenter;
import sz.szsmk.citizencard.ui.adapter.SearchAllAdapter;
import sz.szsmk.citizencard.ui.adapter.SearchTypeAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.fragment.ElecCardSignDialog;
import sz.szsmk.citizencard.ui.newversion.config.Constants;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.StringUtils;

import static sz.szsmk.citizencard.util.Constant.SZ_URL;

/**
 * Copyright (c)2019
 * author: zdh
 * created on: 2019/1/8 19:46
 * description:APP首页搜索跳转
 */
@Route("SearchAllActivity")
public class SearchAllActivity extends IBaseActivity<SearchAllPresenter, SearchAllActivityBinding>
        implements ISearchAllContact.ISearchAllView, View.OnClickListener {


    private String type = "";
    private SearchAllAdapter allAdapter;
    private String keyWord;
    private List<SimpleRes.ResultBean> resultBeans = new ArrayList<>();
    private List<SimpleRes.ResultBean> tempresult = new ArrayList<>();
    private String access_token;

    private int currentPager = 1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.search_all_activity;
    }
    public SearchAllPresenter getmPresenter() {
        return mPresenter;
    }
    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.white).init();
        keyWord = getIntent().getStringExtra(Constant.TYPE);
        dataBinding.searchback.setOnClickListener(this);
        dataBinding.searchEt.setOnClickListener(this);
        dataBinding.searchEt.setText(keyWord);
        dataBinding.nodata.nodataLayout.setVisibility(View.GONE);
        dataBinding.nodata.tvTip.setText(getResources().getString(R.string.no_result));//可以灵活配置无数据文本
        int service = getIntent().getIntExtra("service", 0);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        dataBinding.contentList.setLayoutManager(linearLayoutManager);

        //全部列表
        allAdapter = new SearchAllAdapter(this);
        allAdapter.setBaseInterface(new SearchAllAdapter.BaseInterface() {
            @Override
            public void onClick(View view, String url, String sys_label, double num) {
                access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
                int need_header = (new Double(num)).intValue();
                Bundle bundle1 = new Bundle();
                if (url == null) {
                    return;
                }
                String access_token = ACache.get(SearchAllActivity.this).getAsString("access_token");
                if (access_token == null) {
                    JumpUtils.jump(SearchAllActivity.this, "login", 0);
                } else {
                    if (url.equals("proto:fund")) {
                        mPresenter.selectUserAuth("gjj");
                    } else if (url.equals("proto:social")) {
                        mPresenter.selectUserAuth("sb");
                    } else if (url.equals("proto:osmanthus")) {
                        mPresenter.selectUserAuth("ghf");
                    } else if (url.equals("proto:finance")){
//                        MessageEvent message = new MessageEvent(MessageEvent.CODE_OPENNG);
//                        EventBus.getDefault().post(message);
//                        JumpThirdView.baseToJumpView(activity, url, syslabl, need_header, "")
                        JumpThirdView.baseToJumpView(SearchAllActivity.this, url, sys_label, need_header, "");
                    } else  if (sys_label != null && sys_label.equals("ZZK")) {
                        Bundle bundle=new Bundle();
                        bundle.putString("url", url + "?access_token=" + access_token);
                        JumpUtils.jumptoNatvie(SearchAllActivity.this, "webView", 0, bundle);
                    } else {
                        JumpThirdView.baseToJumpView(SearchAllActivity.this, url, sys_label, need_header, "");

                    }


                }

                //


            }
        });
        dataBinding.contentList.setAdapter(allAdapter);

        dataBinding.swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                tempresult.clear();
                currentPager =1;
                mPresenter.getAll(type, keyWord, currentPager);
            }
        });
        dataBinding.swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getAll(type, keyWord, currentPager);
            }
        });

        if (service == 1) {
            type = "1";
        }
        dataBinding.swipeRefreshLayout.autoRefresh();
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void getAllFail(SimpleRes response) {

        //完成加载并标记没有更多数据
        dataBinding.swipeRefreshLayout.finishLoadMoreWithNoMoreData();
    }

    @Override
    public void getAllSucc(List<SimpleRes.ResultBean> result) {
        dataBinding.contentList.setVisibility(View.VISIBLE);
        dataBinding.nodata.nodataLayout.setVisibility(View.GONE);
        resultBeans = result;
        tempresult.addAll(resultBeans);
        boolean hasMore = false;
        if ("".equals(type)) {
            if (result.size() == 5) {
                if (result.get(0).getDetail().size() == 0 && result.get(1).getDetail().size() == 0
                        && result.get(2).getDetail().size() == 0 && result.get(3).getDetail().size() == 0
                        && result.get(4).getDetail().size() == 0) {
                    resultBeans.clear();
                }
            }

            allAdapter.setViewData(tempresult, 0,currentPager);
            allAdapter.notifyDataSetChanged();
            hasMore = resultBeans.size() == 15;
        }
        if ("1".equals(type)) {
            SimpleRes.ResultBean resultBean1 = resultBeans.get(0);
            resultBeans.clear();
            resultBeans.add(resultBean1);
            if (resultBeans.get(0).getDetail().size() == 0) {
                resultBeans.clear();
            }
            allAdapter.setViewData(tempresult, 1,currentPager);
            allAdapter.notifyDataSetChanged();
            hasMore = resultBeans.get(0).getDetail().size() == 15;
        }
        if ("2".equals(type)) {
            SimpleRes.ResultBean resultBean1 = resultBeans.get(0);
            resultBeans.clear();
            resultBeans.add(resultBean1);
            if (resultBeans.get(0).getDetail().size() == 0) {
                resultBeans.clear();
            }
            allAdapter.setViewData(tempresult, 0,currentPager);
            allAdapter.notifyDataSetChanged();
            hasMore = resultBeans.get(0).getDetail().size() == 15;
        }

        if ("3".equals(type)) {
            SimpleRes.ResultBean resultBean2 = resultBeans.get(0);
            resultBeans.clear();
            resultBeans.add(resultBean2);
            if (resultBeans.get(0).getDetail().size() == 0) {
                resultBeans.clear();
            }
            allAdapter.setViewData(tempresult, 0,currentPager);
            allAdapter.notifyDataSetChanged();
            hasMore = resultBeans.get(0).getDetail().size() == 15;
        }

        if ("4".equals(type)) {
            SimpleRes.ResultBean resultBean3 = resultBeans.get(0);
            resultBeans.clear();
            resultBeans.add(resultBean3);
            if (resultBeans.get(0).getDetail().size() == 0) {
                resultBeans.clear();
            }
            allAdapter.setViewData(tempresult, 1,currentPager);
            allAdapter.notifyDataSetChanged();
            hasMore = resultBeans.size() == 15;
        }

        if ("99".equals(type)) {
            SimpleRes.ResultBean resultBean1 = resultBeans.get(0);
            resultBeans.clear();
            resultBeans.add(resultBean1);
            if (resultBeans.get(0).getDetail().size() == 0) {
                resultBeans.clear();
            }
            allAdapter.setViewData(tempresult, 1,currentPager);
            allAdapter.notifyDataSetChanged();
            hasMore = resultBeans.size() == 15;
        }

        if (hasMore) {
            currentPager++;
        } else {
            //完成加载并标记没有更多数据
            dataBinding.swipeRefreshLayout.finishLoadMoreWithNoMoreData();
        }
        if (resultBeans.size() == 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(700);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dataBinding.contentList.setVisibility(View.GONE);
                                dataBinding.nodata.nodataLayout.setVisibility(View.VISIBLE);
                            }
                        });

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }

    @Override
    public void checkSuccessOrderStatusSucc(String orderStatus) {
        if (orderStatus != null) {
            if (orderStatus.equals("1")) {
                Bundle bundle = new Bundle();
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/charge/main?access_token=" + access_token);
                JumpUtils.jumptoNatvie(SearchAllActivity.this, "webView", 0, bundle);
            } else if (orderStatus.equals("0")) {
                Bundle bundle = new Bundle();
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/charge/guide?access_token=" + access_token);
                JumpUtils.jumptoNatvie(SearchAllActivity.this, "webView", 0, bundle);

            }
        }
    }

    @Override
    public void checkSuccessOrderStatusFail(CloudFlashRes cloudFlashRes) {

    }

    @Override
    public void onClick(View v) {
        tempresult.clear();
        currentPager =1;
        int id = v.getId();
        if (id == R.id.searchback || id == R.id.search_et) {
            finish();
        }
    }


    private String openId;
    @Override
    public void getOpenIdSucc(GetOpenIdRes response) {
        openId = ACache.get(this).getAsString("openId");
        mPresenter.checkIsOpenElecCard(openId);
    }

    @Override
    public void getOpenIdFail(GetOpenIdRes response) {

    }

    @Override
    public void checkIsOpenElecCardSuccess(CheckIsRealName2Res loginResponse) {
        openId = ACache.get(this).getAsString("openId");
        //4.已实名，判断是否已首冲  未实名 弹窗去实名
        if (loginResponse != null) {
            String isRealName = loginResponse.getData().getIsRealName();
            if (isRealName.equals("0")) {

                ACache.get(DaggerApplication.getIns()).put("channelId", "000001");
                mPresenter.preAuthThird(openId, "1");

            } else if (isRealName.equals("1")) {
                mPresenter.queryDzsmkAgreement(openId);
            }
        }
    }

    @Override
    public void checkIsOpenElecCardError(CheckIsRealName2Res preAuthRes) {

    }

    @Override
    public void preAuthThirdSucc(String id) {
        if (id.equals("2")) {
            mPresenter.checkIsCharge();
        } else {
            JumpUtils.jump(this, Constants.SCANQRCODECHECKACTIVITY, 1);
        }
    }

    @Override
    public void preAuthThirdFail(PreAuthThirdRes preAuthRes) {

    }

    @Override
    public void queryDzsmkAgreementFail(QueryDzsmkAgreeMentRes response) {
        if (response.getCode().equals("000005")) {
//            ACache.get(this).put("channelId", "000001");
            mPresenter.preAuthThird(openId, "2");
            dismissLoadingDialog();
        } else {
            PubUtils.popTipOrWarn(this, response.getMessage());

        }
    }

    @Override
    public void checkIsChargeFail() {

    }

    @Override
    public void checkIsChargeSucc(CheckIsChargeRes ibaseBean) {
        dismissLoadingDialog();
        String code = ibaseBean.getCode();
        if (code.equals("0000")) {
            String isReCharge = ibaseBean.getData().getIsReCharge();
            if (isReCharge.equals("1")) {
                JumpUtils.jump(this, "dzsmk", 0);
            } else if (isReCharge.equals("0")) {
                ElecCardSignDialog dialog = new ElecCardSignDialog();
                dialog.setAction(1);
                dialog.show(this.getFragmentManager(), null);
            }
        } else {
            final SuccessDialog dialog = new SuccessDialog(this, ibaseBean.getMessage());
            dialog.show();
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    dialog.cancel();
                }
            }.start();
        }
    }


    @Override
    public void selectUserAuthSucc(SeleciUserAuthRes response, String type) {
        String access_token = ACache.get(this).getAsString("access_token");
        List<SeleciUserAuthRes.AuthTypeListBean> authTypeList = response.getAuthTypeList();

        if (type.equals("gjj")) {
            String isAuth = authTypeList.get(1).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                Bundle bundle = new Bundle();
                bundle.putInt("intotype", 1);
                bundle.putString("choosetype", "gjj");
                JumpUtils.jumptoNatvie(this, "RealNameActivity", 0, bundle);
            } else if (isAuth.equals("1")) {
                Bundle bundle = new Bundle();
                String path = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token;
                bundle.putString("url", path);
                bundle.putString(Constant.CUST_NAME, Constant.ID_NAME);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            } else if (isAuth.equals("0")) {
                String url = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + access_token;
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            }
        }

        if (type.equals("sb")) {
            String isAuth = authTypeList.get(0).getIsAuth();
            //0未授权，1已授权，2未实名(L3认证)
            if (isAuth.equals("2")) {
                Bundle bundle = new Bundle();
                bundle.putInt("intotype", 1);
                bundle.putString("choosetype", "sb");
                JumpUtils.jumptoNatvie(this, "RealNameActivity", 0, bundle);
            } else if (isAuth.equals("1")) {
                Bundle bundle = new Bundle();
                String path = Constant.BASE_URL + "app-front-end/#/social/main?access_token=" + access_token;
                bundle.putString("url", path);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            } else if (isAuth.equals("0")) {
                String url = Constant.BASE_URL + "app-front-end/#/fundAndSociety/authPage?access_token=" + access_token + "&type=1&name=" + Constant.ID_NAME;
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);
            }
        }
        if (type.equals("ghf")) {
            String isAuth = authTypeList.get(2).getIsAuth();
            //0未授权 直接跳 他们网页，1已授权，2未实名(L3认证)
            if (isAuth.equals("0") || isAuth.equals("1")) {

                Bundle bundle = new Bundle();
                //跳转桂花分
                String murl = SZ_URL + "?" + Constant.EXTENT_GHF;
                bundle.putString("url", murl);
                bundle.putString(Constant.TITLE, "桂花分");
                JumpUtils.jumptoNatvie(this, "webView", 0, bundle);

            } else if (isAuth.equals("2")) {
                Bundle bundle = new Bundle();
                bundle.putInt("intotype", 1);
                bundle.putString("choosetype", "ghf");
                JumpUtils.jumptoNatvie(this, "RealNameActivity", 0, bundle);
            }

        }

    }
}
